package com.example.managemyself.ui.ai;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.managemyself.R;
import com.example.managemyself.util.AIHelper;

/**
 * AI设置Fragment，用于配置DeepSeek API
 */
public class AISettingsFragment extends Fragment {
    
    private EditText etApiKey;
    private EditText etApiUrl;
    private EditText etModel;
    private Button btnSave;
    
    public AISettingsFragment() {
        // 必须有一个空的公共构造函数
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ai_settings, container, false);
        
        // 初始化视图
        etApiKey = view.findViewById(R.id.etApiKey);
        etApiUrl = view.findViewById(R.id.etApiUrl);
        etModel = view.findViewById(R.id.etModel);
        btnSave = view.findViewById(R.id.btnSave);
        
        return view;
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 加载当前设置
        loadSettings();
        
        // 设置保存按钮点击事件
        btnSave.setOnClickListener(v -> saveSettings());
    }
    
    /**
     * 加载当前设置
     */
    private void loadSettings() {
        String apiKey = AIHelper.getApiKey(requireContext());
        String apiUrl = AIHelper.getApiUrl(requireContext());
        String model = AIHelper.getModel(requireContext());
        
        etApiKey.setText(apiKey);
        etApiUrl.setText(apiUrl);
        etModel.setText(model);
    }
    
    /**
     * 保存设置
     */
    private void saveSettings() {
        String apiKey = etApiKey.getText().toString().trim();
        String apiUrl = etApiUrl.getText().toString().trim();
        String model = etModel.getText().toString().trim();
        
        // 验证输入
        if (apiKey.isEmpty()) {
            Toast.makeText(requireContext(), "请输入API密钥", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (apiUrl.isEmpty()) {
            Toast.makeText(requireContext(), "请输入API URL", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (model.isEmpty()) {
            Toast.makeText(requireContext(), "请输入模型名称", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 保存设置
        AIHelper.saveApiKey(requireContext(), apiKey);
        AIHelper.saveApiUrl(requireContext(), apiUrl);
        AIHelper.saveModel(requireContext(), model);
        
        Toast.makeText(requireContext(), "设置已保存", Toast.LENGTH_SHORT).show();
    }
} 